﻿using GenericHtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WLFramework.Data;
using WLFramework.DataAccess;
using WLFramework.Json;
using WLFramework.Validation;
using WLFramework.Web;

namespace SampleSite.admin.ajax
{
    /// <summary>
    /// updateModule 的摘要说明
    /// </summary>
    public class updateModule : AjaxHttpHandler
    {
        private class InputData
        {
            [Required]
            public int Id { get; set; }

            [Required]
            public int AppId { get; set; }

            [Required]
            public string GroupName { get; set; }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            InputData input;
            var errors = context.GetModel<InputData>(out input);
            if (errors.Count > 0)
                throw new Exception("参数错误");

            using (PermissionContext db = new PermissionContext())
            {
                var app = db.sys_Applications.Where(k => k.A_ID == input.AppId &&
                                                         k.A_State == 1)
                                             .FirstOrDefault();
                if (app == null)
                    throw new Exception("输入的数据格式不正确");

                var module = db.sys_ModuleList.Where(k => k.M_ID == input.Id &&
                                                          k.M_State == 1)
                                              .FirstOrDefault();
                if (module == null)
                    throw new Exception("输入的数据格式不正确");

                db.BeginTransaction();
                var cmd = DataAccessor.CreateInstance<PermissionCommand>(db);
                var result = cmd.UpdateModule(
                    input.Id,
                    input.GroupName,
                    module.M_EName,
                    module.M_MoudleFormUrl,
                    module.M_IsEdit,
                    module.M_Icon);

                if (result.ErrorID != 0)
                    throw new Exception(result.ErrorMsg);

                db.CommitTransaction();

                context.Response.Write(JSON.Instance.ToJSON(JSONResult.Success));
            }
        }
    }
}